package com.zhkj.txg.module.login.vm

import android.app.Application
import android.os.CountDownTimer
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseApplication
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.http.BaseResponse
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ToastUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.login.entity.LoginResponse
import com.zhkj.txg.module.login.entity.SendCodeResponse
import com.zhkj.txg.module.login.model.CHANGE
import com.zhkj.txg.module.login.model.LOGIN
import com.zhkj.txg.module.login.model.LoginManager

class BindMobileViewModel(application: Application) : BaseViewModel(application) {
    private val manager = LoginManager()
    private var timer: CountDownTimer? = null

    val sendCodeLiveData = MutableLiveData<HttpResponse<SendCodeResponse>>()
    val countDownLiveData: MutableLiveData<Int> = MutableLiveData()
    val pageLiveData = MutableLiveData<Boolean>()
    val bindMobileLiveData = MutableLiveData<HttpResponse<LoginResponse>>()
    val changeMobileLiveData = MutableLiveData<HttpResponse<BaseResponse>>()

    // 上一次输入的手机号码
    var mobile2GetCode: String = ""

    // 类型 0 - 绑定手机号码 1 - 更换手机号码
    var type: Int = 0

    // 用户绑定手机时传入
    var token: String? = null
    var userId: Long = 0

    override fun onCleared() {
        super.onCleared()
        if (timer != null) timer?.cancel()
    }

    fun sendCode(mobile: String, restart: Boolean = false) {
        if (isMobileValid(mobile)) {
            val listener = object : ViewModelSubscribeListener<SendCodeResponse>(sendCodeLiveData) {
                override fun onSuccess(resp: SendCodeResponse) {
                    // 记录获取验证码的手机号
                    mobile2GetCode = mobile
                    // 是否是再次获取验证码
                    resp.restart = restart
                    super.onSuccess(resp)
                    // 开始倒计时
                    startCountDown()
                }
            }
            val sendCode = manager.sendCode(mobile, if (type == 1) CHANGE else LOGIN, listener)
            dispose.add(sendCode)
        }
    }

    fun bindMobile(captcha: String) {
        val listener = object : ViewModelSubscribeListener<LoginResponse>(bindMobileLiveData) {
            override fun onSuccess(resp: LoginResponse) {
                token = resp.data.userInfo.token
                AccountManager.saveToken(resp.data.userInfo.token)
                AccountManager.saveUserId(resp.data.userInfo.user_id.toLong())
                AccountManager.saveNickname(resp.data.userInfo.nickname)
                AccountManager.saveAvatar(resp.data.userInfo.avatar)
                AccountManager.saveMemberStatus(resp.data.isMember)
                super.onSuccess(resp)
            }
        }
        val bindMobile = manager.bindMobile(token ?: "", mobile2GetCode, captcha, listener)
        dispose.add(bindMobile)
    }

    fun changeMobile(captcha: String) {
        val listener = ViewModelSubscribeListener(changeMobileLiveData)
        val changeMobile = manager.changeMobile(AccountManager.getToken(), mobile2GetCode, captcha, listener)
        dispose.add(changeMobile)
    }

    private fun startCountDown() {
        if (timer != null) {
            timer?.cancel()
            timer = null
        }
        timer = object : CountDownTimer(60 * 1000, 1000) {
            override fun onFinish() {
                countDownLiveData.value = 0
            }

            override fun onTick(millisUntilFinished: Long) {
                countDownLiveData.value = (millisUntilFinished / 1000).toInt()
            }
        }
        timer?.start()
    }

    /**
     * 判断手机号码是否正确
     */
    private fun isMobileValid(mobile: String): Boolean {
        val telRegex = "[1]\\d{10}"
        if (TextUtils.isEmpty(mobile) || !mobile.matches(Regex(telRegex))) {
            ToastUtil.show(BaseApplication.INSTANCE.resources.getString(R.string.wrong_mobile))
            return false
        }
        return true
    }
}